package net.da.core.dao.spi.local;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.google.inject.Singleton;

import net.da.core.bof.OrganizationUnit;
import net.da.core.bof.OrganizationUser;
import net.da.core.bof.SysUser;
import net.da.core.dao.OrganisationUserDao;
import net.da.core.entity.OrganisationUserEntity;
import net.da.core.entity.SysUserEntity;
import net.da.core.exception.DaDatabaseException;
import net.da.core.manager.BusinessObjectManagerProvider;

@Singleton
public class OrganisationUserDaoImpl extends AbstractDao implements OrganisationUserDao {

    public OrganizationUser getOrganisationUser(String userName, String password, String organisationUnit) throws DaDatabaseException {
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createNamedQuery("OrganizationUserImpl.findOrgUserForLogin");
            query.setParameter("userName", userName);
            query.setParameter("password", password);
            query.setParameter("organisationUnit", organisationUnit);

            List<OrganisationUserEntity> entities = query.getResultList();
            if (entities.size() > 1) {
                throw new DaDatabaseException(null);
            }
            if (entities.size() == 0) {
                throw new DaDatabaseException(null);
            }

            return BusinessObjectManagerProvider.getBusinessObjectManager().
                        getBusinessObjectByEntity(OrganizationUser.class, entities.get(0));
        } finally {
            em.close();
        }
    }

    public SysUser getSysUser(String userName, String password) throws DaDatabaseException {
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createNamedQuery("SysUserImpl.findUserForLogin");
            query.setParameter("userName", userName);
            query.setParameter("password", password);

            List<SysUserEntity> entities = query.getResultList();
            if (entities.size() > 1) {
                throw new DaDatabaseException(null);
            }
            if (entities.size() == 0) {
                throw new DaDatabaseException(null);
            }

            return BusinessObjectManagerProvider.getBusinessObjectManager().
                        getBusinessObjectByEntity(SysUser.class, entities.get(0));

        } finally {
            em.close();
        }
    }

}
